﻿using System;
using System.Linq;
using System.Collections.Generic;

namespace N2.Workflow.Items
{
	using Details;
	using Integrity;

	[Definition]
	[RestrictParents(typeof(Workflow))]
	[WithEditableName("Name", 01), WithEditableTitle]
	public class StateDefinition :
		ItemContainer<ActionDefinition>,
		IStateDefinition
	{
		string m_iconUrl;
		
		[EditableImage("Icon", 07)]
		public string Icon {
			get {
				return this.m_iconUrl
					?? (this.m_iconUrl = this.GetDetail<string>("Icon", item => this.GetIconUrl()));
			}
			set { this.SetDetail<string>("Icon", this.m_iconUrl = value); }
		}

		public override bool IsPage { get { return false; } }

		public override string Title
		{
			get { return base.Title ?? this.Name; }
		}

		public override string IconUrl { get { return
			this.ID == 0
			? Constants.IconPath + "workflow_states.png"
			: string.IsNullOrEmpty(this.Icon)
				? this.GetIconUrl() ?? base.IconUrl
				: this.Icon; } }
		
		[EditableTypeList("Item State Type", 23, typeof(ItemState),
			Title = "State Type",
			LocalizationClassKey = "Workflow.ActionDefinition")]
		public Type StateType {
			get {
				return Type.GetType(
					this.GetDetail<string>("StateTypeName", typeof(ItemState).AssemblyQualifiedName), false);
			}
			set { this.SetDetail<string>("StateTypeName", value.AssemblyQualifiedName); }
		}

		internal Workflow Workflow { get { return this.Parent as Workflow; } }

		public override string TemplateUrl { get { return "~/Templates/UI/Parts/Empty.ascx"; } }

		#region IStateDefinition Members

		IEnumerable<IActionDefinition> IStateDefinition.Actions {
			get { return this.Items.Cast<IActionDefinition>(); }
		}

		Type IStateDefinition.StateType {
			get { return this.StateType; }
		}

		#endregion

		#region IWorkflowDefinitionItem Members

		IWorkflowDefinition IWorkflowDefinitionItem.Workflow {
			get { return this.Workflow as IWorkflowDefinition; }
		}

		#endregion
	}
}
